package edu.towson.android.graphgrammar.activity.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import edu.towson.android.graphgrammar.IConstants;
import edu.towson.android.graphgrammar.activity.ActivityException;
import edu.towson.android.graphgrammar.activity.IActivityFromManifestReader;

public class ActivityFromManifestReaderImplV1 implements
		IActivityFromManifestReader {

	/**
	 * protected constructor
	 */
	protected ActivityFromManifestReaderImplV1() {
	}

	@Override
	public List<Node> getActivities(File manifestFile) throws ActivityException {
		List<Node> activitiesNodes = null;
		Document document = null;
		try {
			try {
				DocumentBuilderFactory dbFactory = DocumentBuilderFactory
						.newInstance();
				DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
				document = dBuilder.parse(manifestFile);
				document.getDocumentElement().normalize();
			} catch (ParserConfigurationException | SAXException | IOException aie) {
				throw new ActivityException(
						"The manifestfile is not a valid xml", aie);
			}

			NodeList nList = document
					.getElementsByTagName(IConstants.MANIFEST_ACTIVITY_NODE_NAME);
			if (nList != null) {
				activitiesNodes = new ArrayList<Node>();
				for (int temp = 0; temp < nList.getLength(); temp++) {

					Node nNode = nList.item(temp);
					if (nNode.getNodeType() == Node.ELEMENT_NODE) {
						activitiesNodes.add(nNode);

					}
				}
			}

			return activitiesNodes;

		} catch (ActivityException ae) {
			throw ae;
		} catch (Exception e) {
			throw new ActivityException(
					"Failed to get activites from the file", e);
		}
	}

}
